package com.zqcy.workbench.fragment;

import android.app.Activity;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.onemdos.location.MDOSLocation;
import com.onemdos.location.MDOSLocationListener;
import com.onemdos.location.OneMDOSLocationManagerProxy;
import com.onemdos.share.OneMDOSShareAction;
import com.onemdos.share.bean.OneMDOSShareImage;
import com.onemdos.share.bean.OneMDOSWeb;
import com.onemdos.share.constant.ONE_MDOS_SHARE_IMAGE_TYPE;
import com.onemdos.share.constant.ONE_MDOS_SHARE_PLATFORM;
import com.shinemo.base.core.utils.ToastUtil;
import com.shinemo.minisdk.activity.MiniAppActivity;
import com.shinemo.minisdk.config.MiniSdk;
import com.zqcy.workbench.activity.ConfigurationEditActivity;
import com.zqcy.workbench.activity.InformationActivity;
import com.zqcy.workbench.R;
import com.onemdos.banner.common.OneMDOSBannerView;
import com.zqcy.workbench.activity.TransferActivity;
import com.zqcy.workbench.bean.RefreshEvent;
import com.zqcy.workbench.utils.RxBus;
import com.zqcy.workbench.utils.ShareCallBackListener;
import com.zqcy.workbench.adapter.TabAdapter;
import com.zqcy.workbench.bean.TabConfiguration;
import com.zqcy.workbench.utils.Preferences;
import com.zqcy.workbench.utils.ShareDialog;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.zqcy.workbench.utils.Constants.TAB_CONFIGURATION;

public class MainFragment extends Fragment {

    private RelativeLayout bannerLayout;
    private OneMDOSBannerView bannerView;
    private TextView newsShare;
    private ShareDialog shareDialog;
    private RelativeLayout informationView;
    private RelativeLayout serviceView;
    private RecyclerView configurationRecyclerview;
    private TabAdapter tabAdapter;
    private List<TabConfiguration> list = new ArrayList<>(); //存储配置tab数据集
    private TextView locationView;


    public MainFragment() {
        // Required empty public constructor
    }

    public static MainFragment newInstance() {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /**
     * 轮播图的处理 充满父布局高度
     */
    private void initBanner() {
//        int screenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素）
//        int screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight(); // 屏幕高（像素）
        bannerLayout.post(new Runnable() {
            @Override
            public void run() {
                bannerView.setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, bannerLayout.getMeasuredHeight())
                        .requestBanner(getActivity(), "index1")
                        .registerClickListener(data -> {
                        });
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);
        initListener();
        initTabConfiguration();
        initObserver();
    }

    private void initView(View view) {
        bannerLayout = view.findViewById(R.id.banner_layout);
        locationView = view.findViewById(R.id.location_view);
        bannerView = view.findViewById(R.id.banner_view);
        newsShare = view.findViewById(R.id.news_share);
        shareDialog = new ShareDialog(getActivity());
        informationView = view.findViewById(R.id.information_view);
        serviceView = view.findViewById(R.id.service_view);
        configurationRecyclerview = view.findViewById(R.id.configuration_recyclerview);
    }

    private void initTabConfiguration() {
        list.clear();
        list = addMore(Preferences.getDataList(getActivity(), TAB_CONFIGURATION, TabConfiguration.class));
        tabAdapter = new TabAdapter(getActivity(), list);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 5);
        configurationRecyclerview.setLayoutManager(gridLayoutManager);
        configurationRecyclerview.setAdapter(tabAdapter);
        tabAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                TabConfiguration tabConfiguration = (TabConfiguration) adapter.getData().get(position);
                switch (tabConfiguration.getTabId()) {
                    case 6:
                        //转账
                        TransferActivity.startActivity(getActivity());
                        break;
                    case 98:
                        //更多按钮
                        ConfigurationEditActivity.startActivity(getActivity());
                        break;
                    default:
                        ToastUtil.show(getActivity(), getContext().getResources().getString(tabConfiguration.getTabName()));
                        break;
                }
            }
        });
    }


    private void initObserver() {
        Disposable mapDisposable = RxBus.getInstance().doSubscribe(MDOSLocation.class, new Consumer<MDOSLocation>() {
            @Override
            public void accept(MDOSLocation location) throws Exception {
                locationView.setText(location.getCity());
            }
        });

        Disposable disposable = RxBus.getInstance().doSubscribe(RefreshEvent.class, new Consumer<RefreshEvent>() {
            @Override
            public void accept(RefreshEvent refreshEvent) throws Exception {
                if (refreshEvent.isRefresh()) {
                    initTabConfiguration();
                }
            }
        });
        RxBus.getInstance().addSubscription(this, disposable, mapDisposable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getInstance().unSubscribe(this);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 对数据处理并塞入
     *
     * @param list
     * @return
     */
    private List<TabConfiguration> addMore(List<TabConfiguration> list) {
        if (list != null) {
            TabConfiguration tabConfiguration = new TabConfiguration();
            tabConfiguration.setTabIcon(R.mipmap.tab_more);
            tabConfiguration.setTabName(R.string.more);
            tabConfiguration.setTabId(98);
            tabConfiguration.setAdd(false);
            list.add(tabConfiguration);
        }
        return list;
    }


    private void initListener() {
        initBanner();
        initShare();
        initInformation();
        initService();
    }


    private void initService() {
        serviceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //华为测试环境
                MiniSdk.openMiniApp(getActivity(), 17667759, "c1650b7a0b1c3b614b4ebd2c444c9718");
                //本地测试环境
//                MiniSdk.openMiniApp(getActivity(), 19074235, "57f842f1420d84be6a407bd86792daff");
            }
        });
    }

    private void initInformation() {
        informationView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InformationActivity.startActivity(getActivity());
            }
        });
    }

    /**
     * 分享
     */
    private void initShare() {
        shareDialog.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareDialog.dismiss();
            }
        });
        shareDialog.tvWxShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WxShare();
                shareDialog.dismiss();
            }
        });
        shareDialog.tvQqShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                QqShare();
                shareDialog.dismiss();
            }
        });
        shareDialog.tvQqShareImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QqShareImage();
                shareDialog.dismiss();
            }
        });
        shareDialog.tvWBShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WBShare();
                shareDialog.dismiss();
            }
        });
        newsShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() != null && !getActivity().isFinishing()) {
                    shareDialog.show();
                }
            }
        });

    }

    private void WBShare() {
        String wbUrl = "https://zx.sina.cn/sh/2020-11-19/zx-iiznctke2159882.d.html?wm=3049_0172&sendweibouid=2028810631";
        OneMDOSWeb wbWeb = new OneMDOSWeb();
        wbWeb.setTitle("微博测试标题");
        wbWeb.setDescription("微博我就是内容");
        wbWeb.setThumbImageUrl("https://iknow-pic.cdn.bcebos.com/2934349b033b5bb5af05f95232d3d539b700bc48");
//        wbWeb.setThumbImageUrl("https://zx.sina.cn/sh/2020-11-19/zx-iiznctke2159882.d.html?wm=3049_0172&sendweibouid=2028810631");
//                wbWeb.setThumbImageRes(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/WeiXin/test123456.jpg");
        wbWeb.setUrl(wbUrl);
        new OneMDOSShareAction(getActivity())
                .setPlatform(ONE_MDOS_SHARE_PLATFORM.WEI_BO)
                .setCallBack(new ShareCallBackListener(getContext()))
                .withWeb(wbWeb).share();
    }

    private void QqShareImage() {
        String imageUrl = "https://iknow-pic.cdn.bcebos.com/2934349b033b5bb5af05f95232d3d539b700bc48";
        OneMDOSShareImage qqImageUrl = new OneMDOSShareImage();
        qqImageUrl.setImageUrlOrPath(imageUrl);
        qqImageUrl.setType(ONE_MDOS_SHARE_IMAGE_TYPE.URL_INTERNET); //云端 3002
        new OneMDOSShareAction(getActivity())
                .setPlatform(ONE_MDOS_SHARE_PLATFORM.QQ)
                .setCallBack(new ShareCallBackListener(getContext()))
                .withImage(qqImageUrl).share();
    }

    private void QqShare() {
        String qqImagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/WeiXin/test123456.jpg";
        String qqImgUrl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi0.sinaimg.cn%2FIT%2F2009%2F1116%2F2009111674122.jpg&refer=http%3A%2F%2Fi0.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632278562&t=1a0dd414b0d461ecbde585b1cf5edcfd";
        String qqUrl = "https://mbd.baidu.com/newspage/data/landingsuper?context=%7B%22nid%22%3A%22news_9837392514400966103%22%7D&n_type=0&p_from=1";
        OneMDOSWeb qqWeb = new OneMDOSWeb();
        qqWeb.setUrl(qqUrl);
        qqWeb.setTitle("测试标题");
        qqWeb.setDescription("我就是内容");
        qqWeb.setQqImageUrl(qqImgUrl);
        qqWeb.setQqImageLocalUrl(qqImagePath);
        new OneMDOSShareAction(getActivity())
                .setPlatform(ONE_MDOS_SHARE_PLATFORM.QQ)
                .setCallBack(new ShareCallBackListener(getContext()))
                .withWeb(qqWeb).share();
    }

    private void WxShare() {
        String url = "https://mbd.baidu.com/newspage/data/landingsuper?context=%7B%22nid%22%3A%22news_9837392514400966103%22%7D&n_type=0&p_from=1";
        OneMDOSWeb web = new OneMDOSWeb();
        web.setUrl(url);
        web.setTitle("我国首个深空天线组阵系统正式启用！");
        web.setDescription("中国青年报客户端讯（吕炳宏 中青报中青网记者邱晨辉）记者从西安卫星测控中心获悉");
        web.setThumbImageUrl("https://iknow-pic.cdn.bcebos.com/2934349b033b5bb5af05f95232d3d539b700bc48");
        new OneMDOSShareAction(getActivity()).setPlatform(ONE_MDOS_SHARE_PLATFORM.WX).withWeb(web).share();
    }
}